<?php
defined('_JEXEC') or die('Restricted access');
//edited tjs
class igHtmlHelper
{
    function getCategorySelect($name, $key, $value, $exclude, $selectText, $top, $size, $submit, $active, $tree=true)
	{
	    $db	=& JFactory::getDBO();

	    $where = empty($exclude) ? '' : ' WHERE id != '.(int)$exclude;

	    $query = 'SELECT * FROM #__igallery '.$where.' ORDER BY parent, ordering';
		$db->setQuery($query);
		$categories = $db->loadObjectList();

		$children = array();

		if( !empty($categories) )
		{
			if($tree)
			{
				foreach($categories as $category)
				{
					$parent = $category->parent;

					if(@$children[$parent])
					{
						$list = $children[$parent];
					}
					else
					{
						$list = array();
					}

					array_push($list,$category);

					$children[$parent] = $list;
				}
			}
		}

		if($tree)
		{
			$menuTree = JHTML::_('menu.treerecurse', 0, '', array(), $children, 9999, 0, 0 );
		}
		else
		{
			for($i=0; $i<count($categories); $i++)
			{
				$categories[$i]->treename = $categories[$i]->name;
			}
			$menuTree = $categories;
		}

		$selectOptions     = array();

		if($selectText)
		{
		    $selectOptions[]   = JHTML::_('select.option', '0', '- '.JText::_('SELECT CATEGORY').' -', $key, $value);
		}

		if($top)
		{
		    $selectOptions[]   = JHTML::_('select.option', '0', JText::_('Top'), $key, $value );
		}

		foreach($menuTree as $branch)
		{
			$selectOptions[] = JHTML::_('select.option', $branch->id, '&nbsp;&nbsp;&nbsp;'. $branch->treename, $key, $value);
		}

		$html = 'class="inputbox" size="'.$size.'" ';
        $javascript = $submit == true ? 'onchange="document.adminForm.submit();"' : '';

		$parentSelectList = JHTML::_("select.genericlist", $selectOptions, $name, $html.$javascript, $key, $value, $active );
		return $parentSelectList;
	}

	function getUserList($selectedUser)
	{
	    $db	=& JFactory::getDBO();
	    $query = 'SELECT * FROM #__users WHERE block = 0 ORDER BY id';
		$db->setQuery($query);
		$users = $db->loadObjectList();

		for($i=0; $i<count($users); $i++)
		{
			$users[$i]->value = $users[$i]->id;
			$users[$i]->text = $users[$i]->id.' - '.$users[$i]->name.' ('.$users[$i]->username.')';
		}

		$userList = JHTML::_('select.genericlist', $users, 'user', 'class="inputbox" size="1"', 'value', 'text',$selectedUser );

		return $userList;
	}

	function getProfileList($selectedProfile)
	{
	    $db	=& JFactory::getDBO();
	    $query = 'SELECT id AS value, name AS text FROM #__igallery_profiles ORDER BY ordering';
		$db->setQuery($query);
		$profiles = $db->loadObjectList();
		$profileList = JHTML::_('select.genericlist', $profiles, 'profile', 'class="inputbox" size="1"', 'value', 'text',$selectedProfile );

		return $profileList;
	}

	function getACLSelect($name, $selected, $checkFrontendEnabled=true)
	{
		$configArray =& JComponentHelper::getParams('com_igallery');
		$disabled = $checkFrontendEnabled == true && $configArray->get('allow_frontend_creation', 0) == 0 ? true : false;
		$selected = $disabled == true ? 0 : $selected;
		
		$acl =& JFactory::getACL();
		$selectOptions = array();
		$selectOptions[] = JHTML::_('select.option', 2, JText::_('ALL'),'value','text',$disabled );
		$selectOptions[] = JHTML::_('select.option', 0, JText::_('NOBODY'),'value','text',$disabled );
		$selectOptions[] = JHTML::_('select.option', 1, JText::_('OWNER'),'value','text',$disabled );
		

		$gtree = $acl->get_group_children_tree( null, 'Public Frontend', false );
		foreach($gtree as $branch)
		{
			$selectOptions[] = JHTML::_('select.option', $branch->value, $branch->text,'value','text',$disabled);
		}

		$db	=& JFactory::getDBO();
	    $query = 'SELECT * FROM #__users WHERE block = 0 ORDER BY id';
		$db->setQuery($query);
		$users = $db->loadObjectList();

		for($i=0; $i<count($users); $i++)
		{
			$selectOptions[] = JHTML::_('select.option', $users[$i]->id, $users[$i]->id.' - '.$users[$i]->name.' ('.$users[$i]->username.')','value','text',$disabled);
		}
		
		$list 	= JHTML::_('select.genericlist', $selectOptions, $name.'[]', 'size="10" multiple="multiple" '.$disabled, 'value', 'text', $selected );

		return $list;
	}

	function moderateImage($row, $i, $backend)
	{
		$img 	= $row->moderate ? 'tick.png' : 'unmoderate.png';
		$task 	= $row->moderate  ? 'unmoderate' : 'moderate';
		$alt 	= $row->published ? JText::_( 'MODERATE' ) : JText::_( 'UNMODERATE' );

		$href = '';
		if($backend)
		{
			$href .= '<a href="javascript:void(0);" onclick="return listItemTask(\'cb'. $i .'\',\''. $task .'\')" title="'. $alt .'">';
		}

		$href .= '<img src="'. IG_IMAGE_ASSET_PATH. $img .'" border="0" alt="'. $alt .'" />';

		if($backend)
		{
			$href .= '</a>';
		}

		return $href;
	}

	function getGalleryDimensions($mainFiles, $lboxFiles, $profile)
	{
        //work out the largest width/height of the images
        $largestHeight = 0;
		$largestWidth = 0;
		$largestLboxHeight = 0;
		$largestLboxWidth = 0;

        for ($i=0; $i<count($mainFiles); $i++)
		{
		    $largestWidth = $mainFiles[$i]['width'] > $largestWidth ? $mainFiles[$i]['width'] : $largestWidth;
		    $largestHeight = $mainFiles[$i]['height'] > $largestHeight ? $mainFiles[$i]['height'] : $largestHeight;
		    $largestLboxWidth = $lboxFiles[$i]['width'] > $largestLboxWidth ? $lboxFiles[$i]['width'] : $largestLboxWidth;
		    $largestLboxHeight = $lboxFiles[$i]['height'] > $largestLboxHeight ? $lboxFiles[$i]['height'] : $largestLboxHeight;
        }

		//if the width/height has been manually set in the backend then override
		$largestWidth      = $profile->img_container_width > $largestWidth ? $profile->img_container_width : $largestWidth;
		$largestHeight     = $profile->img_container_height > $largestHeight ? $profile->img_container_height : $largestHeight;
		$largestLboxWidth  = $profile->lbox_img_container_width > $largestLboxWidth ? $profile->lbox_img_container_width : $largestLboxWidth;
		$largestLboxHeight = $profile->lbox_img_container_height > $largestLboxHeight ? $profile->lbox_img_container_height : $largestLboxHeight;
        
		//work out the overall gallery width
		
		$galleryLboxWidth = $largestLboxWidth;
		
        if($profile->show_large_image == 1)
        {
			$galleryWidth = $largestWidth;
		}
        else
        {
        	if($profile->thumb_container_width != 0)
        	{
        		$galleryWidth = $profile->thumb_container_width;
        	}
        	else
        	{
        		$thumbRowCount = $profile->images_per_row == 0 ? count($mainFiles) : $profile->images_per_row;
            	$galleryWidth = ($profile->thumb_width + 20) * $thumbRowCount;
        	}
        }

		//if the thumbs or descriptions are set to left/right, add on some width
		if( ($profile->photo_des_position == 'left' || $profile->photo_des_position == 'right') && $profile->show_descriptions == 1)
		{
		    $desWidth = $profile->photo_des_width == 0 ? 200 : $profile->photo_des_width;
		    $galleryWidth = $galleryWidth + $desWidth;
		}

		if( ($profile->thumb_position == 'left' || $profile->thumb_position == 'right') && $profile->show_thumbs == 1 && $profile->show_large_image == 1)
		{
		    $thumbRowCount = $profile->images_per_row == 0 ? count($mainFiles) : $profile->images_per_row;
            $profile->thumb_container_width = $profile->thumb_container_width == 0 ? ($profile->thumb_width + 20) * $thumbRowCount : $profile->thumb_container_width;

			$galleryWidth = $galleryWidth + $profile->thumb_container_width;
		}

		if( ($profile->lbox_photo_des_position == 'left' || $profile->lbox_photo_des_position == 'right') && $profile->lbox_show_descriptions == 1)
		{
		    $desWidth = $profile->lbox_photo_des_width == 0 ? 200 : $profile->lbox_photo_des_width;
			$galleryLboxWidth = $galleryLboxWidth + $desWidth;
		}

		if( ($profile->lbox_thumb_position == 'left' || $profile->lbox_thumb_position == 'right') && $profile->lbox_show_thumbs == 1)
		{
		    $thumbRowCount = $profile->lbox_images_per_row == 0 ? count($mainFiles) : $profile->lbox_images_per_row;
            $profile->lbox_thumb_container_width = $profile->lbox_thumb_container_width == 0 ? ($profile->lbox_thumb_width + 20) * $thumbRowCount : $profile->lbox_thumb_container_width;

			$galleryLboxWidth = $galleryLboxWidth + $profile->lbox_thumb_container_width;
		}

        //if the top/bottom description/thumbs width is wider than the current width, make the width bigger
	    if($profile->photo_des_width > $galleryWidth && $profile->show_descriptions == 1 && ($profile->photo_des_position == 'top' || $profile->photo_des_position == 'bottom') )
	    {
	       $galleryWidth =  $profile->photo_des_width;
	    }

	    if($profile->thumb_container_width > $galleryWidth && $profile->show_thumbs == 1 && ($profile->thumb_position == 'top' || $profile->thumb_position == 'bottom'))
	    {
	       $galleryWidth =  $profile->thumb_container_width;
	    }

	    if($profile->lbox_photo_des_width > $galleryLboxWidth && $profile->lbox_show_descriptions == 1 && ($profile->lbox_photo_des_position == 'top' || $profile->lbox_photo_des_position == 'bottom') )
	    {
	       $galleryLboxWidth =  $profile->lbox_photo_des_width;
	    }

	    if($profile->lbox_thumb_container_width > $galleryLboxWidth && $profile->lbox_show_thumbs == 1 && ($profile->lbox_thumb_position == 'top' || $profile->lbox_thumb_position == 'bottom'))
	    {
	       $galleryLboxWidth =  $profile->lbox_thumb_container_width;
	    }

	    //add 10 pixels for large_img padding
	    $galleryWidth = $galleryWidth + 10;
		$galleryLboxWidth = $galleryLboxWidth + 10;

		//add 14px for grey border shadow css
		if($profile->style == 'grey-border-shadow')
		{
            $galleryWidth = $galleryWidth + 14;
            $largestWidth = $largestWidth + 14;
		    $largestHeight = $largestHeight + 14;

		    $galleryLboxWidth = $galleryLboxWidth + 14;
		    $largestLboxWidth  = $largestLboxWidth + 14;
		    $largestLboxHeight = $largestLboxHeight + 14;
		}

		$sizesArray = array();
		$sizesArray['largestWidth'] = $largestWidth;
		$sizesArray['largestHeight'] = $largestHeight;
		$sizesArray['galleryWidth'] = $galleryWidth;
		$sizesArray['largestLboxWidth'] = $largestLboxWidth;
		$sizesArray['largestLboxHeight'] = $largestLboxHeight;
		$sizesArray['galleryLboxWidth'] = $galleryLboxWidth;

        return $sizesArray;

	}

	function makeHeadJs($category, $profile, $photoList, $ratingsList, $galleryWidth,
	$galleryLboxWidth, $mainFiles, $lboxFiles, $source = 'component', $id)
	{
	    $user =& JFactory::getUser();
	    $guest = $user->get('guest') ? 1 : 0;

	    $configArray =& JComponentHelper::getParams('com_igallery');

	    $headJs = '
		//make arrays and classes for the category: '.$category->name.' (id= '.$id.')
		window.addEvent(\'load\', function()
		{
        ';

		$headJs .= 		'var idArray'.$id.' = [';
		for($n=0;$n<count($photoList);$n++)
		{
			$headJs .= $photoList[$n]->id.',';
		}
		$headJs = substr($headJs,0,-1);
		$headJs .= '];
		';

		$headJs .= 		'
		var ratedArray'.$id.' = [';
		for($i=0;$i<count($photoList);$i++)
		{
			$match = false;
			for($m=0;$m<count($ratingsList);$m++)
			{
				if($photoList[$i]->id == $ratingsList[$m]->img_id)
				{
					if($ratingsList[$m]->author == $user->username)
					{
						$headJs .= '1,';
						$match = true;
						break;
					}
				}
			}
			if($match == false)
			{
				$headJs .= '0,';
			}
		}
		$headJs = substr($headJs,0,-1);
		$headJs .= '];
		';

		$ratingsArray = array();
		$counter = array();

		for($i=0;$i<count($photoList);$i++)
		{
			$counter[$i] = 0;

			for($m=0;$m<count($ratingsList);$m++)
			{
				if($photoList[$i]->id == $ratingsList[$m]->img_id)
				{
					if( isset($ratingsArray[$i]) )
					{
						$ratingsArray[$i] = $ratingsArray[$i] + $ratingsList[$m]->rating;
					}
					else
					{
						$ratingsArray[$i] = $ratingsList[$m]->rating;
					}

					$counter[$i]++;
				}
			}

			if( isset($ratingsArray[$i]) )
			{
				$ratingsArray[$i] = round( ($ratingsArray[$i]/$counter[$i]) * 2) /2;
			}
			else
			{
				$ratingsArray[$i] = 0;
			}
		}

		$headJs .= '
		var ratingsArray'.$id.' = [';
		for($i=0;$i<count($ratingsArray);$i++)
		{
			$headJs .= $ratingsArray[$i].',';
		}
		$headJs = substr($headJs,0,-1);
		$headJs .= '];
		';

		$headJs .= '
		var ratingsCounterArray'.$id.' = [';
		for($i=0;$i<count($ratingsArray);$i++)
		{
			$headJs .= $counter[$i].',';
		}
		$headJs = substr($headJs,0,-1);
		$headJs .= '];
		';

		//images json part
		$headJs .= '

		var jsonImagesObject'.$id.' =
		{
			"main":
			[
			';

		for($i=0; $i<count($photoList); $i++)
		{
			$headJs .= '	{"filename": "'.$mainFiles[$i]['folderName'].'/'.$mainFiles[$i]['fullFileName'].'", "width": '.$mainFiles[$i]['width'].', "height": '.$mainFiles[$i]['height'].', "alt": "'.$photoList[$i]->alt_text.'"},
			';
		}
		$headJs = substr($headJs,0,-5);
		$headJs .= '
		],';

		$headJs .= '

			"lbox":
			[
			';

		for($i=0; $i < count($photoList); $i++)
		{
			$headJs .= '	{"filename": "'.$lboxFiles[$i]['folderName'].'/'.$lboxFiles[$i]['fullFileName'].'", "width": '.$lboxFiles[$i]['width'].', "height": '.$lboxFiles[$i]['height'].', "alt": "'.$photoList[$i]->alt_text.'"},
			';
		}
		$headJs = substr($headJs,0,-5);
		$headJs .= '
			]
		};';

		$headJs .= '

		var igalleryMain'.$id.' = new igalleryClass({
			allowComments: '.$profile->allow_comments.',
			allowRating: '.$profile->allow_rating.',
			alRatingsContainer: \'main_alratings'.$id.'\',
			catid: \''.$id.'\',
			closeImage: \'closeImage'.$id.'\',
			commentsAmount: \'main_comments_amount'.$id.'\',
			commentsContainer: \'main_comments_container'.$id.'\',
			commentsForm: \'main_img_comment_form'.$id.'\',
			commentsImgId: \'main_comment_img_id'.$id.'\',
			commentsLoadingGif: \'main_ajax_comment_gif'.$id.'\',
			commentsLimit: 60,
			ratingsLimit: 20,
			commentsMessageContainer: \'main_comments_message_container'.$id.'\',
			commentsTextarea: \'main_comment_textarea'.$id.'\',
			desContainer: \'main_des_container'.$id.'\',
			downArrow: \'main_down_arrow'.$id.'\',
			facebookShare: '.$profile->share_facebook.',
			facebookContainer: \'main_facebook_share'.$id.'\',
			host: \''.IG_HOST.'\',
			fadeDuration: '.$profile->fade_duration.',
			guest: '.$guest.',
			idArray: idArray'.$id.',
			imageAssetPath: \''.IG_IMAGE_ASSET_PATH.'\',
			jCommentsMain: \'main_jcomments_wrapper'.$id.'\',
			jCommentsLbox: \'lbox_jcomments_wrapper'.$id.'\',
			joomCommentContainer: \'main_joomcomment_wrapper'.$id.'\',
			jsonImages: jsonImagesObject'.$id.',
			jsonImagesImageType: jsonImagesObject'.$id.'.main,
			large_image: \'main_large_image'.$id.'\',
			lboxDark: \'lbox_dark'.$id.'\',
			lboxWhite: \'lbox_white'.$id.'\',
			lightboxWidth: '.$galleryLboxWidth.',
			leftArrow: \'main_left_arrow'.$id.'\',
			lightboxOn: '.$profile->lightbox.',
			magnify: '.$profile->magnify.',
			main: 1,
			mainWrapper: \'main_images_wrapper'.$id.'\',
			moderateComments: '.$configArray->get('moderate_comment', 0).',
			downloadType: \''.$profile->download_image.'\',
			downloadId: \'main_download_link'.$id.'\',
			numPics: '.count($photoList).',
			numRatings: \'main_num_ratings'.$id.'\',
			preload: '.$profile->preload.',
			ratedArray: ratedArray'.$id.',
			ratingsArray: ratingsArray'.$id.',
			ratingsCounterArray: ratingsCounterArray'.$id.',
			ratingsContainer: \'main_ratings_container'.$id.'\',
			ratingsForm: \'main_rating_form'.$id.'\',
			ratingsImgId: \'main_ratings_img_id'.$id.'\',
			ratingsImgRating: \'main_img_rating'.$id.'\',
			ratingsMessageContainer: \'main_ratings_message_container'.$id.'\',
			refreshMode: \''.$profile->refresh_mode.'\',
			reportImage: '.$profile->report_image.',
			reportContainer: \'main_report'.$id.'\',
			resize_path: \''.IG_IMAGE_HTML_RESIZE.'\',
			rightArrow: \'main_right_arrow'.$id.'\',
			scrollBoundary: '.$profile->scroll_boundary.',
			scrollSpeed: '.$profile->scroll_speed.',
			showDescriptions: '.$profile->show_descriptions.',
			showUpDown: '.$profile->arrows_up_down.',
			showLeftRight: '.$profile->arrows_left_right.',
			showLargeImage: '.$profile->show_large_image.',
			showTags: '.$profile->show_tags.',
			showThumbs: '.$profile->show_thumbs.',
			showSlideshowControls: '.$profile->show_slideshow_controls.',
			slideshowAutostart: '.$profile->slideshow_autostart.',
			slideshowForward: \'slideshow_forward'.$id.'\',
			slideshowPause: '.$profile->slideshow_pause.',
			slideshowPlay: \'slideshow_play'.$id.'\',
			slideshowRewind: \'slideshow_rewind'.$id.'\',
			style: \''.$profile->style.'\',
			tagsContainer: \'main_tags_container'.$id.'\',
			thumbContainer: \'main_thumb_container'.$id.'\',
			thumbTable: \'main_thumb_table'.$id.'\',
			thumbPostion: \''.$profile->thumb_position.'\',
			thumbScrollbar: '.$profile->thumb_scrollbar.',
			upArrow: \'main_up_arrow'.$id.'\'
        });
		';
		if($profile->lightbox == 1)
		{
			$headJs .= '
		var igalleryLbox'.$id.' = new igalleryClass({
			allowComments: '.$profile->lbox_allow_comments.',
			allowRating: '.$profile->lbox_allow_rating.',
			alRatingsContainer: \'lbox_alratings'.$id.'\',
			catid: \''.$id.'\',
			closeImage: \'closeImage'.$id.'\',
			commentsAmount: \'lbox_comments_amount'.$id.'\',
			commentsContainer: \'lbox_comments_container'.$id.'\',
			commentsForm: \'lbox_img_comment_form'.$id.'\',
			commentsImgId: \'lbox_comment_img_id'.$id.'\',
			commentsLoadingGif: \'lbox_ajax_comment_gif'.$id.'\',
			commentsLimit: 60,
			ratingsLimit: 20,
			commentsMessageContainer: \'lbox_comments_message_container'.$id.'\',
			commentsTextarea: \'lbox_comment_textarea'.$id.'\',
			desContainer: \'lbox_des_container'.$id.'\',
			downArrow: \'lbox_down_arrow'.$id.'\',
			facebookShare: '.$profile->lbox_share_facebook.',
			facebookContainer: \'lbox_facebook_share'.$id.'\',
			host: \''.IG_HOST.'\',
			fadeDuration: '.$profile->lbox_fade_duration.',
			guest: '.$guest.',
			idArray: idArray'.$id.',
			imageAssetPath: \''.IG_IMAGE_ASSET_PATH.'\',
			jsonImages: jsonImagesObject'.$id.',
			jsonImagesImageType: jsonImagesObject'.$id.'.lbox,
			joomCommentContainer: \'lbox_joomcomment_wrapper'.$id.'\',
			large_image: \'lbox_large_image'.$id.'\',
			lboxDark: \'lbox_dark'.$id.'\',
			lboxWhite: \'lbox_white'.$id.'\',
			lightboxWidth: '.$galleryLboxWidth.',
			leftArrow: \'lbox_left_arrow'.$id.'\',
			lightboxOn: '.$profile->lightbox.',
			lboxScalable: '.$profile->lbox_scalable.',
			mainWrapper: \'lbox_white'.$id.'\',
			magnify: '.$profile->magnify.',
			main: 0,
			moderateComments: '.$configArray->get('moderate_comment', 0).',
			downloadType: \''.$profile->lbox_download_image.'\',
			downloadId: \'lbox_download_link'.$id.'\',
			numPics: '.count($photoList).',
			numRatings: \'lbox_num_ratings'.$id.'\',
			preload: '.$profile->lbox_preload.',
			ratedArray: ratedArray'.$id.',
			ratingsArray: ratingsArray'.$id.',
			ratingsCounterArray: ratingsCounterArray'.$id.',
			ratingsContainer: \'lbox_ratings_container'.$id.'\',
			ratingsForm: \'lbox_rating_form'.$id.'\',
			ratingsImgId: \'lbox_ratings_img_id'.$id.'\',
			ratingsImgRating: \'lbox_img_rating'.$id.'\',
			ratingsMessageContainer: \'lbox_ratings_message_container'.$id.'\',
			resize_path: \''.IG_IMAGE_HTML_RESIZE.'\',
			refreshMode: \'javascript\',
			reportImage: '.$profile->lbox_report_image.',
			reportContainer: \'lbox_report'.$id.'\',
			rightArrow: \'lbox_right_arrow'.$id.'\',
			scrollBoundary: '.$profile->lbox_scroll_boundary.',
			scrollSpeed: '.$profile->lbox_scroll_speed.',
			showDescriptions: '.$profile->lbox_show_descriptions.',
			showUpDown: '.$profile->lbox_arrows_up_down.',
			showLeftRight: '.$profile->lbox_arrows_left_right.',
			showLargeImage: '.$profile->show_large_image.',
			showThumbs: '.$profile->lbox_show_thumbs.',
			showTags: '.$profile->lbox_show_tags.',
			showSlideshowControls: '.$profile->lbox_show_slideshow_controls.',
			slideshowAutostart: '.$profile->lbox_slideshow_autostart.',
			slideshowForward: \'lbox_slideshow_forward'.$id.'\',
			slideshowPause: '.$profile->lbox_slideshow_pause.',
			slideshowPlay: \'lbox_slideshow_play'.$id.'\',
			slideshowRewind: \'lbox_slideshow_rewind'.$id.'\',
			style: \''.$profile->style.'\',
			tagsContainer: \'lbox_tags_container'.$id.'\',
			thumbContainer: \'lbox_thumb_container'.$id.'\',
			thumbPostion: \''.$profile->lbox_thumb_position.'\',
			thumbTable: \'lbox_thumb_table'.$id.'\',
			thumbScrollbar: '.$profile->lbox_thumb_scrollbar.',
			upArrow: \'lbox_up_arrow'.$id.'\'

		});

		igalleryMain'.$id.'.lboxGalleryObject = igalleryLbox'.$id.';
		igalleryLbox'.$id.'.mainGalleryObject = igalleryMain'.$id.';
		';
		}
		$headJs .= '
		});
		';

		return $headJs;
	}

	function writeBreadcrumbs($category)
	{
	    global $mainframe;
	    $db	=& JFactory::getDBO();

	    $pathway =& $mainframe->getPathway();

		$breadCrumbs = array();
		$breadCrumbsLinks = array();

		$Itemid = JRequest::getInt('Itemid', null);
		if( !is_null($Itemid) )
		{
            $menu = $mainframe->getMenu();
            $active = $menu->getActive();
            $idOfMenuCategory = (isset($active->query['id'])) ? $active->query['id'] : $active->id;
		}
		else
		{
		    $idOfMenuCategory = 0;
		}

        if($category->id != $idOfMenuCategory)
		{
            $breadCrumbs[] = $category->name;
            $breadCrumbsLinks[] = '';

            if($category->parent != 0)
            {
                $query = 'SELECT * FROM #__igallery WHERE id = '.(int)$category->parent;
                $db->setQuery($query);
                $bcCategory = $db->loadObject();

                if($bcCategory->id != $idOfMenuCategory)
		        {
                    array_unshift($breadCrumbs, $bcCategory->name);
                    array_unshift($breadCrumbsLinks, JRoute::_('index.php?option=com_igallery&amp;view=igcategory&amp;id='.$bcCategory->id) );

                    while($bcCategory->parent != 0)
                    {
                    	$query = 'SELECT * FROM #__igallery WHERE id = '.(int)$bcCategory->parent;
                    	$db->setQuery($query);
                    	$bcCategory = $db->loadObject();

                    	if($bcCategory->id == $idOfMenuCategory)
		                {
		                    break;
		                }

		                array_unshift($breadCrumbs, $bcCategory->name);
                    	array_unshift($breadCrumbsLinks, JRoute::_('index.php?option=com_igallery&amp;view=igcategory&amp;id='.$bcCategory->id) );
		            }
		        }
            }
		}

        for($i=0; $i<count($breadCrumbs); $i++)
		{
			$pathway->addItem($breadCrumbs[$i], $breadCrumbsLinks[$i]);
		}
	}

	function gTreeRecurse($id, $list, &$children, $maxlevel=9999, $level=0)
	{
	    if (@$children[$id] && $level <= $maxlevel)
    	{
    		foreach ($children[$id] as $v)
    		{
    			$id = $v->id;

    			$list[$id] = $v;

    	        if($v->parent != $id)
    	        {
    		        $list[$v->parent]->children[$v->id] = $v;
    			}
    			else
    			{
        			$list[$id]->children = array();
    			}

    			$list = igHtmlHelper::gTreeRecurse($id,$list,$children,$maxlevel,$level+1);
    		}
    	}
    	return $list;
	}

	function flattenNestedList($children,$needle = false,$collection = array())
	{
	    foreach($children as $k => $v)
        {
            if(!empty($v->children)) {
                $collection = igHtmlHelper::flattenNestedList($v->children,$needle,$collection);
            }

            if(is_array($needle)) {
                $ret = array();
                foreach($needle as $n)
                {
                    $ret[$n] = $v->$n;
                }
                $collection[] = $ret;
            }
            else
            {
                $collection[] = $v->id;
            }
        }

        return $collection;
    }

    function getChildList($parentId,$type = 'nested')
	{
	    $db =& JFactory::getDBO();
	    $query = 'SELECT g.* FROM #__igallery AS g WHERE g.published = 1 '.
	    'ORDER BY g.parent, g.ordering';
        $db->setQuery($query);

        $mitems = $db->loadObjectList();

        $children = array();

        if($mitems)
        {
            $list = array();

            foreach($mitems as $v)
            {
                $pt = $v->parent;
                $list = @$children[$pt] ? $children[$pt] : array();
                array_push($list,$v);
                $children[$pt] = $list;
            }

            $collection = igHtmlHelper::gTreeRecurse(0,array(),$children,9999,0);

            if( isset($collection[$parentId]->children) )
            {
                $result = $collection[$parentId]->children;

                if($type == 'flat')
                {
                    $result = igHtmlHelper::flattenNestedList($result);
                }
            }
            else
            {
                $result = array();
            }
        }

        JArrayHelper::toInteger($result);

        return $result;
	}
	
	function getFolderList()
	{
		$configArray =& JComponentHelper::getParams('com_igallery');
		$configPath = $configArray->get('import_server_base', 'images');
		
		$path = JPATH_SITE.DS.$configPath;
		$folderArray = JFolder::listFolderTree($path, '.', 5);
		
		$options = array();
		$options[] = JHTML::_('select.option', '', JText::_('SELECT FROM LIST') );
		foreach($folderArray as $folder)
		{
			$options[] = JHTML::_('select.option', $folder['relname'], $folder['relname']);
		}
		
		$selectlist = JHTML::_('select.genericlist', $options, 'server_import', 'class="inputbox" size="1"');
		
		return $selectlist;
	}
	
	function getItemid($catId)
	{
		global $mainframe;
		
		$menu = $mainframe->getMenu();
		$menuItems = $menu->getMenu();
		
		$igMenuItems = array();
		
		//get all of the menu items that link to a category
		//as $igMenuItems[itemid] = catid
		foreach($menuItems as $key => $value)
		{
			if($value->component == 'com_igallery' && $value->query['view'] == 'igcategory')
			{
				$igMenuItems[$value->id] = $value->query['id'];
			}
		}
		
		//if there are none, return the current itemid
		if(count($igMenuItems) == 0)
		{
			return JRequest::getVar('Itemid', 1);
		}
		
		//if there is one, return that itemid
		if(count($igMenuItems) == 1)
		{
			return key($igMenuItems);
		}
		
		//if there is more than one...
		if(count($igMenuItems) > 1)
		{
			//if one of the menu items links to the target cat, then return that
			foreach($igMenuItems as $key => $value)
			{
				if($value == $catId)
				{
					return $key;
				}
			}
			
			//otherwise get all of the target cat's parents
			$parentCats = array();
			$db	=& JFactory::getDBO();
			
			$query = 'SELECT * FROM #__igallery WHERE id = '.$catId;
            $db->setQuery($query);
            $row = $db->loadObject();

            while($row->parent != 0)
            {
                $query = 'SELECT * FROM #__igallery WHERE id = '.(int)$row->parent;
                $db->setQuery($query);
                $row = $db->loadObject();
                $parentCats[] = $row->id;
            }
            
            //for each menu item, loop through all the parents and try to find a match
			foreach($igMenuItems as $key => $value)
			{
				for($i=0; $i<count($parentCats); $i++)
				{
					if($value == $parentCats[$i])
					{
						return $key;
					}
				}
			}
			
			//if nothing can be found, return the current itemid
			return JRequest::getVar('Itemid', 1);
		}
	}
}